#include "evaluate_dialog.h"
#include <QFile>
#include <QTextStream>
#include <QMessageBox>
#include <QIntValidator>

EvaluateDialog::EvaluateDialog(QWidget *parent, bool readOnly) : QDialog(parent), m_readOnly(readOnly)
{
    ui.setupUi(this);
    loadStudents();
    connect(ui.btnBack, &QPushButton::clicked, this, &QDialog::accept);
    if (!m_readOnly) {
        connect(ui.tableWidget, &QTableWidget::cellChanged, this, [=](int row, int col) {
            if (col == 3) {
                QString val = ui.tableWidget->item(row, col)->text();
                bool ok = false;
                int score = val.toInt(&ok);
                if (!ok || score < 0 || score > 100) {
                    QMessageBox::warning(this, "无效成绩", "请输入0~100的数字");
                    ui.tableWidget->item(row, col)->setText("");
                    return;
                }
                saveStudents();
            }
        });
    }
}

void EvaluateDialog::loadStudents()
{
    ui.tableWidget->setRowCount(0);
    QFile file("students.txt");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) return;
    QTextStream in(&file);
    int row = 0;
    while (!in.atEnd()) {
        QString line = in.readLine().trimmed();
        if (line.isEmpty()) continue;
        QStringList parts = line.split(",");
        if (parts.size() >= 3) {
            ui.tableWidget->insertRow(row);
            QTableWidgetItem *item0 = new QTableWidgetItem(parts[0].trimmed());
            QTableWidgetItem *item1 = new QTableWidgetItem(parts[1].trimmed());
            QTableWidgetItem *item2 = new QTableWidgetItem(parts[2].trimmed());
            QTableWidgetItem *item3 = new QTableWidgetItem(parts.size() >= 4 ? parts[3].trimmed() : "");
            item0->setFlags(item0->flags() & ~Qt::ItemIsEditable);
            item1->setFlags(item1->flags() & ~Qt::ItemIsEditable);
            item2->setFlags(item2->flags() & ~Qt::ItemIsEditable);
            item3->setFlags(item3->flags() & ~Qt::ItemIsEditable);
            ui.tableWidget->setItem(row, 0, item0);
            ui.tableWidget->setItem(row, 1, item1);
            ui.tableWidget->setItem(row, 2, item2);
            ui.tableWidget->setItem(row, 3, item3);
            row++;
        }
    }
}

void EvaluateDialog::saveStudents()
{
    int rowCount = ui.tableWidget->rowCount();
    QFile file("students.txt");
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) return;
    QTextStream out(&file);
    for (int i = 0; i < rowCount; ++i) {
        QStringList parts;
        for (int j = 0; j < 4; ++j) {
            QTableWidgetItem *item = ui.tableWidget->item(i, j);
            parts << (item ? item->text().trimmed() : "");
        }
        out << parts.join(",") << "\n";
    }
} 